package com.yequan.compare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author yq
 * @date 2020/08/25
 */
public class TestCompare {

    public static void main(String[] args) {
        List<Person> personListForComparable = initData();
        List<Person> personListForComparator = initData();
        Person a = new Person(1, 67, "a");
        Person b = new Person(6, 6, "b");
        comparableCompareTo(a, b);
        sortByAge(personListForComparable);
        sortByIdAsc(personListForComparator);
        sortByIdDesc(personListForComparator);
    }

    /**
     * 初始化数据
     *
     * @return
     */
    private static List<Person> initData() {
        List<Person> personList = new ArrayList<>();
        Person a = new Person(1, 67, "a");
        Person b = new Person(6, 6, "b");
        Person c = new Person(5, 46, "c");
        Person d = new Person(3, 22, "d");
        personList.add(a);
        personList.add(b);
        personList.add(c);
        personList.add(d);
        return personList;
    }

    /**
     * 基于comparable接口的compareTo方法进行比较
     * x.compareTo(y) < 0 : 表示x小于y
     * x.compareTo(y) = 0 : 表示x等于y
     * x.compareTo(y) > 0 : 表示x大于y
     */
    private static void comparableCompareTo(Person x, Person y) {
        if (x.compareTo(y) < 0) {
            System.out.println(x.getName() + "年龄小于" + y.getName());
        } else if (x.compareTo(y) == 0) {
            System.out.println(x.getName() + "年龄等于" + y.getName());
        } else {
            System.out.println(x.getName() + "年龄大于" + y.getName());
        }
    }

    /**
     * 基于comparable接口的compareTo方法进行排序
     *
     * @param personList
     */
    private static void sortByAge(List<Person> personList) {
        System.out.println("排序前：" + personList);
        Collections.sort(personList);
        System.out.println("排序前：" + personList);
    }

    /**
     * 基于Comparator接口的compare方法进行升序排序
     *
     * @param personList
     */
    private static void sortByIdAsc(List<Person> personList) {
        System.out.println("升序排序前：" + personList);
        Collections.sort(personList, new AscIdComparator());
        System.out.println("升序排序前：" + personList);
    }

    /**
     * 基于Comparator接口的compare方法进行降序排序
     *
     * @param personList
     */
    private static void sortByIdDesc(List<Person> personList) {
        System.out.println("降序排序前：" + personList);
        Collections.sort(personList, new DescIdComparator());
        System.out.println("降序排序前：" + personList);
    }

}
